import 'dart:convert';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../constants.dart';
import '../../route/router.dart';
import '../app/app_view_model.dart';
import 'auth_view_model.dart';

class AuthViewForm extends StatefulWidget {
  const AuthViewForm({super.key});

  @override
  State<AuthViewForm> createState() => _AuthViewFormState();
}

class _AuthViewFormState extends State<AuthViewForm> {
  final formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    loadCaptcha();
  }

  void loadCaptcha() {
    final model = context.read<AuthViewModel>();
    model.toggleCaptcha();
  }

  @override
  Widget build(final BuildContext context) {
    final model = context.read<AuthViewModel>();
    final theme = FluentTheme.of(context);
    return Form(
      key: formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        children: [
          SizedBox(height: 20.h),
          //标题
          Text('登录', style: theme.typography.titleLarge),
          //输入框
          buildInputs(model),
          //按钮
          SizedBox(height: 6.h),
          buildButtons(model, theme),
        ],
      ),
    );
  }

  Widget buildCaptcha() => Consumer<AuthViewModel>(
        builder: (_, model, __) {
          final b64Captcha = model.b64Captcha;
          if (b64Captcha.isNotEmpty) {
            final img = Image.memory(
              base64Decode(b64Captcha.split(',')[1]),
              width: constants.captchaSizeWidth,
              height: constants.captchaSizeHeight,
              fit: BoxFit.fill,
              gaplessPlayback: true,
            );
            return MouseRegion(
              cursor: SystemMouseCursors.click,
              child: GestureDetector(
                child: img,
                onTap: () {
                  final controller = model.getController(LoginField.captcha);
                  if (controller != null) {
                    controller.clear();
                  }
                  //刷新验证码
                  loadCaptcha();
                },
              ),
            );
          }
          return SizedBox.shrink();
        },
      );

  Widget buildInputs(final AuthViewModel model) {
    Widget buildPrefix(LoginField field) => Container(
          alignment: Alignment.center,
          padding: EdgeInsets.only(left: 6.w),
          margin: EdgeInsets.only(right: 5.w),
          width: 20.w,
          height: 36.h,
          child: Icon(field.iconData, size: 13.sp),
        );
    List<Widget> buildInput(LoginField field) {
      final Widget input;
      if (field == LoginField.passwd) {
        input = PasswordFormBox(
          leadingIcon: buildPrefix(field),
          revealMode: PasswordRevealMode.peekAlways,
          controller: model.getController(field),
          placeholder: field.label,
          initialValue: field.val ?? '',
          validator: (val) => field.validHandler(val),
        );
      } else {
        input = TextFormBox(
          controller: model.getController(field),
          prefix: buildPrefix(field),
          placeholder: field.label,
          validator: (val) => field.validHandler(val),
          suffix: field == LoginField.captcha ? buildCaptcha() : null,
        );
      }
      return [input, SizedBox(height: 16.h)];
    }

    return Padding(
      padding: EdgeInsets.only(left: 30.w, top: 16.h, right: 30.w),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          for (final LoginField field in LoginField.values)
            ...buildInput(field),
        ],
      ),
    );
  }

  Widget buildButtons(final AuthViewModel model, final FluentThemeData theme) =>
      Row(
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.only(top: 28.h, left: 20.w, right: 20.w),
              child: FilledButton(
                child: Padding(
                  padding: const EdgeInsets.all(2),
                  child: Text(
                    '登录',
                    style: theme.typography.caption?.copyWith(
                      fontSize: 16.sp,
                      color: Colors.white,
                    ),
                  ),
                ),
                onPressed: () {
                  if (formKey.currentState?.validate() ?? false) {
                    final appModel = context.read<AppViewModel>();
                    model.toggleLogin(
                      appModel,
                      () => AppRote.dashboard.go(context),
                    );
                  }
                },
              ),
            ),
          ),
        ],
      );
}
